package com.csci.feishuapp.demo3.utils;

import com.google.gson.*;

import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;

public class CustomGsonBuilder {

    private static final GsonBuilder gsonBuilder = new GsonBuilder().registerTypeAdapter(Date.class, new DateTypeAdapter());

    public static Gson createGson() {
        return gsonBuilder.create();
    }

    static class DateTypeAdapter implements JsonSerializer<Date>, JsonDeserializer<Date> {
        @Override
        public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
            /*final String DEFAULT_DATE_TIME_SS_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SS";
            String dateString = json.getAsString();
            LocalDateTime.from(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_SS_FORMAT).parse(dateString))
            toLocalDateTime(convertDateFormat(date), DEFAULT_DATE_TIME_SS_FORMAT);
            Date.from(target.atZone(ZoneId.systemDefault()).toInstant());*/
            return DateUtils.toDate(DateUtils.toLocalDateTime(json.getAsString()));
        }

        @Override
        public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return new JsonPrimitive(simpleDateFormat.format(src));
        }
    }

}
